package com.ken.elmssm.service.impl;


import com.ken.elmssm.bean.Admin;
import com.ken.elmssm.bean.Role;
import com.ken.elmssm.bean.RoleAdmin;
import com.ken.elmssm.common.ElmException;
import com.ken.elmssm.mapper.AdminMapper;
import com.ken.elmssm.mapper.RoleAdminMapper;
import com.ken.elmssm.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.management.RuntimeMBeanException;
import java.util.List;

@Service
@Transactional(rollbackFor = ElmException.class)
public class AdminServiceImpl extends DefaultServiceImpl<Admin> implements AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private RoleAdminMapper roleAdminMapper;

    @Override
    public Admin login(Admin admin) {
        Admin ret = null;
        try {
            ret = adminMapper.login(admin);
        }catch (Exception e) {
            e.printStackTrace();
            throw new ElmException("登录异常",e);
        }
        return ret;
    }

    @Override
    public boolean add(Admin object) {
        boolean ret = false;
        // 多表关联数据更新，经常会操作多个表格，这组操作构成一个事务；
        try {
            ret= adminMapper.add(object);
            if(ret) {
                List<Role> list = object.getRoles();
                for(Role role : list) {
                    ret &= roleAdminMapper.add(new RoleAdmin(null, role.getRoleId(), object.getAdminId()));
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
            throw new ElmException("新增管理员或分配角色异常",e);
        }
        return ret;
    }

    @Override
    public boolean deleteById(Integer id) {
        boolean ret = false;
        if(id == 1) {
            throw new ElmException("超级账号不能删除");
        }else {
            try {
                // 先删除管理员的角色，再删除管理员信息
                roleAdminMapper.deleteByAdmin(new Admin(id, null, null));
                // 注意必须使用super进行调用，避免死循环
                ret = super.deleteById(id);
            }catch (RuntimeMBeanException e) {
                e.printStackTrace();
                throw new ElmException("删除管理员失败",e);
            }
        }
        return ret;
    }

    @Override
    public boolean edit(Admin object) {
        boolean ret = false;
        try {
            // 修改密码和盐
            ret = super.edit(object);
            // 修改角色- 先删除后新增(可以编写其它逻辑进行功能实现： 先判断再删除和新增)
            ret &= roleAdminMapper.deleteByAdmin(object);
            List<Role> list = object.getRoles();
            for(Role role : list){
                ret &= roleAdminMapper.add(new RoleAdmin(null,role.getRoleId(),object.getAdminId()));
            }
        }catch (RuntimeException e) {
            e.printStackTrace();
            throw new ElmException("修改密码或角色异常");
        }
        return ret;
    }
}
